import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { Repository } from 'typeorm';
import { Role } from '../role/entities/role.entity';
import { Authority } from '../authority/entities/authority.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { UsersEntity } from '../users/users.entity';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
    @InjectRepository(Authority)
    private readonly authorityRepository: Repository<Authority>,
    @InjectRepository(UsersEntity)
    private readonly userRepository: Repository<UsersEntity>,
  ) {}

  create(createRoleDto: CreateRoleDto) {
    return 'This action adds a new role';
  }

  async findAll() {
    const qb1 = await this.roleRepository
      .createQueryBuilder('u')
      .leftJoinAndSelect('u.users', 'r')
      .leftJoinAndSelect('u.authority', 'c')
      .getMany();

    const qb = await this.roleRepository
      .createQueryBuilder('u')
      .leftJoinAndSelect('u.users', 'r')
      .leftJoinAndSelect('u.authority', 'c')
      .getMany();
    return qb;
  }

  findOne(id: number) {
    return `This action returns a #${id} role`;
  }

  async update(id: number, updateRoleDto: UpdateRoleDto) {
    console.log(UpdateRoleDto, updateRoleDto);

    const aa = await this.roleRepository.findOne(id, {
      relations: ['authority'],
    });

    await this.roleRepository
      .createQueryBuilder()
      .relation('authority')
      .of(id)
      .addAndRemove(
        updateRoleDto.radio,
        aa.authority.map((item) => item.id),
      );
    return `成功`;
  }

  remove(id: number) {
    return `This action removes a #${id} role`;
  }

  //查找角色所有权限
  async findAux(roleCode: string): Promise<Role> {
    return this.roleRepository
      .createQueryBuilder('role')
      .where('role.code = :code', { code: roleCode })
      .leftJoinAndSelect('role.authority', 'authority')
      .getOne();
  }
}
